Multilevel inheritance in Java occurs when a class inherits from a class, and then another class inherits from that derived class. This type of inheritance forms a parent-child relationship in a chained or linear way. A minimum of three classes are involved in multilevel inheritance.
Here’s an example of multilevel inheritance in Java:
multilevel inheritance example in Java
// Superclass
class Person {
Person() {
System.out.println("Person constructor");
}
void nationality() {
System.out.println("Indian");
}
void place() {
System.out.println("Mumbai");
}
}
// Subclass 1
class Emp extends Person {
Emp() {
System.out.println("Emp constructor");
}
void organization() {
System.out.println("IBM");
}
void place() {
System.out.println("New York");
}
}
// Subclass 2
class Manager extends Emp {
Manager() {
System.out.println("Manager constructor");
}
void subordinates() {
System.out.println(12);
}
void place() {
System.out.println("London");
}
}
public class Main {
public static void main(String arg[]) {
Manager m = new Manager();
m.nationality(); // method from Person class
m.organization(); // method from Emp class
m.subordinates(); // method from Manager class
m.place(); // method from Manager class
}
}
Output
Person constructor
Emp constructor
Manager constructor
Indian
IBM
12
London
In this example, Emp is a subclass that extends the Person superclass, and Manager is another subclass that extends the Emp class. The Manager class inherits the nationality() method from the Person class, the organization() method from the Emp class, and it also defines its own methods subordinates() and place()2. In the main method, an object m of type Manager is created. This object can call the nationality() method, the organization() method, the subordinates() method, and the place() method.
Another example of multi-level inheriatance to understand easily
Example of multi-level inheriatance using animal and dog
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Puppy extends Dog{
void sleep(){System.out.println("sleeping...");}
}
class Main{
public static void main(String args[]){
Puppy obj=new Puppy();
obj.sleep();
obj.bark();
obj.eat();
}
}
Output
sleeping...
barking...
eating...
As you can see in the example given above, puppy class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.
This is a simple demonstration of how multilevel inheritance works in Java. It allows for code reusability and reduces code duplication.